import Taro, { useLoad } from '@tarojs/taro';
import { Input, Text, View } from '@tarojs/components';
import { BoxShadow, Button, Empty, Header, Icon, ScrollView, Space, TopView } from 'pd-taro-ui';
import LoadNextView from 'pd-taro-ui/ScrollView/LoadNextView';
import ToTopView from 'pd-taro-ui/ScrollView/ToTopView';
import { PageParams } from './route.config';
import { useRouterData } from '@/utils/router';
import { FormikHelpers, FormikProps } from 'formik';
import { useRef, useState } from 'react';
import { string, object, array } from 'yup';
import { Form, FormItem } from 'pd-taro-form';
import { useReactive } from 'ahooks';
import { asyncTimeOut, flatFormikErrors } from '@/utils/util';
import './index.scss';

interface MyFormValues {
  email?: string;
}
interface ListItem {
  id: string;
}

const prefix = 'TODOListPage__';
const ListPage = () => {
  const router = useRouterData();
  const pageParams = router.params as PageParams;
  const state = useReactive({
    isSearchMore: false,
    scrollTop: 0,
    refresh: false,
    hadNextPage: false,
    loading: false,
    page: 1,
    pageSize: 30,
    list: [] as ListItem[],
  });
  const formikRef = useRef<FormikProps<MyFormValues>>(null);
  const initialValues: MyFormValues = {
    email: '',
  };

  useLoad(() => {
    onRefresh();
  });

  const onSubmit = async (values: MyFormValues, formikHelpers: FormikHelpers<MyFormValues>) => {
    console.log('onSubmit', values);
    onRefresh();
  };

  const queryList = async (page: number) => {
    console.log('queryList');
    if (!formikRef.current?.isValid) {
      Taro.showToast({ icon: 'none', title: Object.values(formikRef.current?.errors!)[0] as string });
      return;
    }
    state.loading = true;
    if (page === 1) {
      state.list = [];
      state.refresh = true;
    }
    state.page = page;
    // TODO
    await asyncTimeOut(1000).then(() => {});
    state.loading = false;
    state.refresh = false;
    const list: ListItem[] = [];
    for (let i = 0; i < state.pageSize; i++) {
      list.push({ id: `${page}_${i}` });
    }
    state.hadNextPage = list.length === state.pageSize;
    if (page === 1) {
      state.list = list;
    } else {
      state.list = state.list.concat(list);
    }
  };

  const onRefresh = () => {
    if (state.loading) return;
    console.log('onRefresh');
    queryList(1);
  };

  const onScrollToLower = () => {
    if (!state.hadNextPage || state.loading) return;
    console.log('onScrollToLower', state.page);
    queryList(state.page + 1);
  };

  const renderForm = () => {
    return (
      <Form
        innerRef={formikRef}
        validationSchema={object({
          email: string().nullable().required('email不能为空'),
        })}
        initialValues={initialValues}
        onSubmit={onSubmit}
        labelWidth={240}
        direction='horizontal'>
        {({ errors, values, handleChange, submitForm, isValid, resetForm }) => {
          return (
            <View style={{ padding: 12 }}>
              <FormItem type='Input' label='文本框' name='email' placeholder='请输入' required clearable />
              <FormItem type='Input' label='文本框' name='email' placeholder='请输入' required clearable />
              {state.isSearchMore && (
                <>
                  <FormItem type='Input' label='文本框' name='email' placeholder='请输入' required clearable />
                </>
              )}
              <Space row style={{ marginTop: 12 }} justify='end'>
                <Button
                  loading={state.loading}
                  type='primary'
                  onClick={() => {
                    if (!isValid) {
                      Taro.showToast({ icon: 'none', title: flatFormikErrors(errors)[0] });
                      return;
                    }
                    submitForm();
                  }}>
                  查询
                </Button>
                <Button loading={state.loading} onClick={resetForm}>
                  重置
                </Button>
                <Button
                  style={{ borderWidth: 0 }}
                  onClick={() => {
                    state.isSearchMore = !state.isSearchMore;
                  }}>
                  {state.isSearchMore ? '收起' : '展开'}
                </Button>
              </Space>
            </View>
          );
        }}
      </Form>
    );
  };

  return (
    <TopView>
      <Header title='表单页demo' titleCenter />
      <ScrollView
        scrollTop={state.scrollTop}
        onReload={onRefresh}
        onRefresh={onRefresh}
        onScrollToLower={onScrollToLower}
        refresh={state.refresh}
        onScroll={(e: any) => {
          state.scrollTop = e.detail.scrollTop;
        }}
        lowerThreshold={80}>
        {renderForm()}

        {state.list.map((item, index) => {
          return (
            <View className={prefix + 'list__item'} key={index}>
              {item.id}
            </View>
          );
        })}

        {!state.list.length && <Empty />}
        <LoadNextView visible={!state.refresh && state.hadNextPage} loading={state.loading} />
      </ScrollView>
      <ToTopView visible={state.scrollTop > 300} onClick={() => (state.scrollTop = 0)} />
    </TopView>
  );
};
export default ListPage;
